let express = require("express");
let router = express.Router();

let { Article } = require("../models/index");

//  /article/  post请求 才会匹配这个路由

// 登录校验

// 调用这个接口的时候，后端验证前端是否传入token了，如果没有传入
// 提示请登录-权限不够，如果传入token-验证token是否正确
//

let jwt = require("jsonwebtoken");
let loginVerify = require("../middlware/loginVerify");

// post 后面可以传入多个中间件（函数）
// 发布文章 --文章的标题 内容 发布作者
router.post("/", loginVerify, async function (req, res) {
  console.log("发布文章接口");
  console.log(req.body.title);
  console.log(req.body.content);
  console.log(req.uid);
  //
  let art = new Article({
    ...req.body, //将body 中属性给了 当前对象
    author: req.uid,
  });
  await art.save();

  res.json({ code: 1, msg: "发布文章成功" });
});

// 删除文章  restful api
// ----   /article/1  删除id为1的文章 (restful api  )
// /article?id=12
router.delete("/:id", loginVerify, async function (req, res) {
  console.log("删除文章接口");
  console.log(req.params.id); //获取/article/1 请求路径里面的id
  console.log(req.query.id); //获取/article?id=12 请求路径里面的id

  let r = await Article.findByIdAndDelete(req.params.id);

  console.log(r);
  if (r) {
    res.json({ code: 1, msg: "删除文章成功" });
  } else {
    res.json({ code: 0, msg: "文章不存在" });
  }
});

// 修改文章接口
router.patch("/:id", loginVerify, async function (req, res) {
  console.log("修改文章接口");
  console.log(req.params.id); //获取/article/1 请求路径里面的id
  console.log(req.body);

  let r = await Article.findByIdAndUpdate(req.params.id, { ...req.body });

  res.json({ code: 1, msg: "修改文章接口" });
});

// 分页查询文章接口
// pageSize  pageNum uid
// /article?pageSize=10&pageNum=1?uid=1
router.get("/", async function (req, res) {
  let pageSize = req.query.pageSize || 1;
  let pageNum = req.query.pageNum || 10;
  let uid = req.query.uid;
  let queryObj = {};
  if (uid) {
    queryObj = { ...queryObj, author: uid };
  }

  let arts = await Article.find(queryObj)
    // 关联 用户表的数据 到 当前查询结果-- 不显示密码
    .populate("author", { password: 0 })
    .skip((pageNum - 1) * pageSize)
    .limit(pageSize);
  console.log(arts);
  res.json({ code: 1, data: arts });
});
// 根据id查询文章详情接口
router.get("/:article_id", async (req, res) => {
  let art = await Article.findById(req.params.article_id).populate("author", {
    password: 0,
  });
  res.json({ code: 1, data: art });
});

/* 
router.post("/", function (req, res) {
  console.log(req.headers);
  let token = req.headers["token"];
  if (!token) {
    res.json({ code: 0, msg: "请登录-请传入token" });
  } else {
    jwt.verify(token, "zz123", function (err, data) {
      if (err) {
        console.log(err, "token 验证失败");
        res.json({ code: 0, msg: "token 验证失败" });
      } else {
        console.log(data, "token验证成功");
        res.json({ code: 1, msg: "发布文章成功" });
      }
    });
  }
}); 

*/

// 评论 发布-删除-修改-查询

module.exports = router;
